import axios from 'axios'
import lrz from 'lrz'
import { Indicator, MessageBox, Toast} from 'mint-ui'

export async function loadImages (e) {
  return readFile(e)
}

export async function readFile(e) {
  var uploadImages = e.target.files

  if (!uploadImages || uploadImages.length <= 0) { return }
  var p = new Promise((resolve, reject) => {
    createImage(uploadImages, e).then(function(data) {
      resolve(data)
    }), function(err) {
      reject(err)
    }
  })
  return p
}

function createImage(file, e) {
  let vm = this
  let imageArr = []
  const fileLength = file.length
  var p = new Promise((resolve, reject) => {
    for (var i = 0; i < file.length; i++) {
      lrz(file[i], { width: 750 }).then(function(rst) {
        let obj = rst.base64
        let blob = changeToB(obj.split(',')[1])

        const response = uploadImages(blob)
        response.then(result => {
          if (result.status === 0) {
            let path = result.data.path
            imageArr.push(path)
          } else {
            Toast('上传图片失败')
          }
          if (fileLength === imageArr.length) {
            resolve(imageArr)
          }
        }).cacth(err => {
          Toast('上传图片失败')
          reject(err)
        })
      }).always(function() {
   // 清空文件上传控件的值
        e.target.value = null
      })
    }
  })
  return p
}

function changeToB(b64Data, sliceSize = 512) {
  const byteCharacters = atob(b64Data)
  const byteArrays = []

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize)

    const byteNumbers = new Array(slice.length)
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }

    const byteArray = new Uint8Array(byteNumbers)
    byteArrays.push(byteArray)
  }

    // 单位m
  let lengthNum = byteArrays.length * 512 / 1024 / 1024

  if (lengthNum >= 2) {
      // window.alert('图片太大，无法上传')
  }
  const blob = new Blob(byteArrays, {type: 'image/jpeg'})

  return blob
}

// function uploadImage(e) {
//   return new Promise((resovle, reject => {
//     const formData = new FormData()
//     formData.append('file', e)
//     const options = {
//       url: '/api/file/upload',
//       method: 'post',
//       data: formData,
//       headers: {
//         'Content-Type': 'multipart/form-data'
//       }
//     }
  //   this.$axios(options).then(result => {
  //     resovle(result)
  //   }).cacth(e => {
  //     reject(e)
  //   })
  // })

//     this.isShowProgress = true

// }

export async function uploadImages(e) {
  const formData = new FormData()
  formData.append('file', e)
  const options = {
    url: '/user/v1/file/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }

  // axios(options).then(response => {

  //   if (response.status === 0) {
  //     console.log('response2')
  //     console.log(response)
  //     return response
  //   } else {
  //     Toast('上传图片失败')
  //   }
  // }).catch(err => {
  //   Indicator.close()
  //   Toast('上传图片失败')
  // })
  Indicator.open()
  const promise = await axios(options)
  Indicator.close()
  return promise
  // axios(options).then(result => {
  //   resolve({name: '1'})
  // }).cacth(e => {
  //   reject(e)
  // })
}
